package com.alibaba.citrus.cr.mn.order.center.facade.adapter.impl;

import com.alibaba.citrus.cr.mn.order.center.facade.adapter.ItemQueryAdapter;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ItemGroupAbilityRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ItemSearchAbilityRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.request.ItemUnitAbilityRequest;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.ItemGroupAbilityDTO;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.ItemSearchAbilityDTO;
import com.alibaba.citrus.cr.mn.order.center.facade.adapter.dataobject.response.ItemUnitAbilityDTO;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.cz.base.tool.result.Result;
import com.alibaba.cz.item.normal.scitem.api.ScItemSearchAbilityService;
import com.alibaba.cz.item.normal.scitem.model.openapi.*;
import com.alibaba.cz.item.normal.scitem.model.search.ScItemSearchAbilityRequest;
import com.alibaba.cz.item.normal.scitem.model.search.ScItemSearchAbilityResponse;
import com.alibaba.cz.item.normal.scitem.model.search.ScItemSearchReqAbilityDTO;
import com.alibaba.cz.item.normal.scitem.openapi.IScItemUnitAbilityService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.middleware.cache.runtime.service.EpochCacheService;
import com.epoch.app.bcorder.contants.BcOrderConstants;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author zhangxiaorui
 * @ClassName ItemQueryAdapterImpl
 * @description: TODO
 * @date 2023/05/31 21:04
 * @version: 1.0
 */
@Service
public class ItemQueryAdapterImpl implements ItemQueryAdapter {
    private static final Log log = Log.getLogger(ItemQueryAdapterImpl.class);

    @DubboReference
    private IScItemUnitAbilityService iScItemUnitAbilityService;
    @DubboReference
    private ScItemSearchAbilityService scItemSearchAbilityService;
    @Resource
    private EpochCacheService epochCacheService;

    @Override
    public List<ItemSearchAbilityDTO> queryItem(ItemSearchAbilityRequest itemSearchAbilityRequest) {
        if (CollectionUtils.isEmpty(itemSearchAbilityRequest.getProductCodes())) {
            return Lists.newArrayList();
        }
        ScItemSearchAbilityRequest scItemSearchAbilityRequest = new ScItemSearchAbilityRequest();
        ScItemSearchReqAbilityDTO searchReqDTO = new ScItemSearchReqAbilityDTO();
        searchReqDTO.setOuterIdList(itemSearchAbilityRequest.getProductCodes());
        searchReqDTO.setStatusList(Collections.singletonList(1));
        scItemSearchAbilityRequest.setSearchReqDTO(searchReqDTO);
        scItemSearchAbilityRequest.setPageSize(itemSearchAbilityRequest.getProductCodes().size());

        Result<ScItemSearchAbilityResponse> result = scItemSearchAbilityService.searchFromDB(scItemSearchAbilityRequest);
        log.info("货品查询 request={}, result={}", JSON.toJSONString(scItemSearchAbilityRequest), JSONObject.toJSONString(result));
        if (Objects.isNull(result) || Objects.isNull(result.getResult()) || CollectionUtils.isEmpty(result.getResult().getSearchResult())) {
            return Lists.newArrayList();
        }

        return result.getResult().getSearchResult().stream().map(p -> {
            ItemSearchAbilityDTO itemSearch = new ItemSearchAbilityDTO();
            BeanUtils.copyProperties(p, itemSearch);
            // 从features里获取商品相关信息
            itemSearch.setUnit(parseFeatureMap(p.getFeatures(), "unit"));
            itemSearch.setUnitCode(parseFeatureMap(p.getFeatures(), "unitName"));
            itemSearch.setProductCode(parseFeatureMap(p.getFeatures(), "productCode"));
            itemSearch.setCategoryCode(parseFeatureMap(p.getFeatures(), "category"));
            itemSearch.setCategoryDesc(parseFeatureMap(p.getFeatures(), "categoryDesc"));
            itemSearch.setCategoryChildCode(parseFeatureMap(p.getFeatures(), "categoryChildCode"));
            itemSearch.setCategoryChildDesc(parseFeatureMap(p.getFeatures(), "categoryChildDesc"));
            return itemSearch;
        }).collect(Collectors.toList());
    }

    private String parseFeatureMap(Map<String, String> featuresMap, String key) {
        if(MapUtils.isEmpty(featuresMap)) {
            return null;
        }
        return featuresMap.getOrDefault(key, null);
    }

    @Override
    public List<ItemUnitAbilityDTO> queryScItemUnitMap(ItemUnitAbilityRequest itemUnitAbilityRequest) {
        // 增加缓存，防止并发测试时item的cpu被打满
        String uniqueKey = "ScItemUnit:" +
                itemUnitAbilityRequest.getUnitCode() + "_" +
                itemUnitAbilityRequest.getUnitName() + "_" +
                itemUnitAbilityRequest.getStart() + "_" +
                itemUnitAbilityRequest.getLimit();
        String scItemUnitList = epochCacheService.get(BcOrderConstants.REDIS_CACHE_CODE(), uniqueKey);
        log.info("货品单位查询 缓存结果 scItemUnitList={}", scItemUnitList);
        if (StringUtils.isNotBlank(scItemUnitList)) {
            List<ItemUnitAbilityDTO> itemUnitAbilityDTOS = new ArrayList<>();
            for (Object scItemUnit : JSON.parseArray(scItemUnitList)) {
                itemUnitAbilityDTOS.add(JSON.parseObject(((JSON) scItemUnit).toJSONString(), ItemUnitAbilityDTO.class));
            }
            return itemUnitAbilityDTOS;
        }

        ScItemUnitAbilityRequest scItemUnitAbilityRequest = new ScItemUnitAbilityRequest();
        scItemUnitAbilityRequest.setUnitCode(itemUnitAbilityRequest.getUnitCode());
        scItemUnitAbilityRequest.setUnitName(itemUnitAbilityRequest.getUnitName());
        scItemUnitAbilityRequest.setLimit(itemUnitAbilityRequest.getLimit());
        scItemUnitAbilityRequest.setStart(itemUnitAbilityRequest.getStart());
        ResultWrapper<List<ScItemUnitAbilityResponse>> listResultWrapper = iScItemUnitAbilityService.selectScItemUnit(scItemUnitAbilityRequest);
        log.info("货品单位查询 request={}, result={}",
                JSON.toJSONString(scItemUnitAbilityRequest), JSONObject.toJSONString(listResultWrapper));
        if (Objects.isNull(listResultWrapper) || CollectionUtils.isEmpty(listResultWrapper.getResult())) {
            return Lists.newArrayList();
        }
        List<ItemUnitAbilityDTO> itemUnitAbilityDTOS = listResultWrapper.getResult().stream().map(p -> {
            ItemUnitAbilityDTO itemUnitAbilityDTO = new ItemUnitAbilityDTO();
            BeanUtils.copyProperties(p, itemUnitAbilityDTO);
            return itemUnitAbilityDTO;
        }).collect(Collectors.toList());

        // 缓存结果，10分钟过期
        epochCacheService.put(BcOrderConstants.REDIS_CACHE_CODE(), uniqueKey, JSON.toJSONString(itemUnitAbilityDTOS), 10L, TimeUnit.MINUTES);

        return itemUnitAbilityDTOS;
    }

    @Override
    public List<ItemGroupAbilityDTO> queryScItemGroup(ItemGroupAbilityRequest itemGroupAbilityRequest) {
        // 增加缓存，防止并发测试时item的cpu被打满
        String uniqueKey = "ScItemGroup:" +
                itemGroupAbilityRequest.getProductGroupCode() + "_" +
                itemGroupAbilityRequest.getProductGroupName() + "_" +
                itemGroupAbilityRequest.getStart() + "_" +
                itemGroupAbilityRequest.getLimit();
        String scItemGroupList = epochCacheService.get(BcOrderConstants.REDIS_CACHE_CODE(), uniqueKey);
        log.info("货品组查询 缓存结果 scItemGroupList={}", scItemGroupList);
        if (StringUtils.isNotBlank(scItemGroupList)) {
            List<ItemGroupAbilityDTO> itemGroupAbilityDTOS = new ArrayList<>();
            for (Object scItemGroup : JSON.parseArray(scItemGroupList)) {
                itemGroupAbilityDTOS.add(JSON.parseObject(((JSON) scItemGroup).toJSONString(), ItemGroupAbilityDTO.class));
            }
            return itemGroupAbilityDTOS;
        }

        ScItemGroupAbilityRequest scItemGroupAbilityRequest = new ScItemGroupAbilityRequest();
        scItemGroupAbilityRequest.setProductGroupCode(itemGroupAbilityRequest.getProductGroupCode());
        scItemGroupAbilityRequest.setProductGroupName(itemGroupAbilityRequest.getProductGroupName());
        scItemGroupAbilityRequest.setStart(itemGroupAbilityRequest.getStart());
        scItemGroupAbilityRequest.setLimit(itemGroupAbilityRequest.getLimit());
        ResultWrapper<List<ScItemGroupAbilityResponse>> listResultWrapper = iScItemUnitAbilityService.selectScItemGroup(scItemGroupAbilityRequest);
        log.info("货品组查询 request={}, result={}",
                JSON.toJSONString(scItemGroupAbilityRequest), JSONObject.toJSONString(listResultWrapper));
        if(Objects.isNull(listResultWrapper) || CollectionUtils.isEmpty(listResultWrapper.getResult())) {
            return Lists.newArrayList();
        }
        List<ItemGroupAbilityDTO> itemGroupAbilityDTOS = listResultWrapper.getResult().stream().map(p -> {
            ItemGroupAbilityDTO groupAbilityDTO = new ItemGroupAbilityDTO();
            BeanUtils.copyProperties(p, groupAbilityDTO);
            return groupAbilityDTO;
        }).collect(Collectors.toList());

        // 缓存结果，10分钟过期
        epochCacheService.put(BcOrderConstants.REDIS_CACHE_CODE(), uniqueKey, JSON.toJSONString(itemGroupAbilityDTOS), 10L, TimeUnit.MINUTES);

        return itemGroupAbilityDTOS;
    }

}
